package fr.cephb.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;

public class IOUtils
	{
	public static void copyTo(InputStream in, OutputStream out)
		throws IOException
		{
		byte buff[]=new byte[2048];
		int n;
		while((n=in.read(buff))!=-1)
			{
			out.write(buff, 0, n);
			}
		out.flush();
		}
	
	public static void copyTo(Reader in, Writer out)
	throws IOException
		{
		char buff[]=new char[2048];
		int n;
		while((n=in.read(buff))!=-1)
			{
			out.write(buff, 0, n);
			}
		out.flush();
		}
	
	public static String getReaderContent(Reader r)
	throws IOException
		{
		StringWriter sw=new StringWriter();
		copyTo(r, sw);
		return sw.toString();
		}
	
	private static boolean isURL(String uri)
		{
		return 	uri.startsWith("http://") ||
				uri.startsWith("https://") ||
				uri.startsWith("file://") ||
				uri.startsWith("ftp://")
				;
		}
	
	public static InputStream openInputStream(String filename)
		throws IOException
		{
		InputStream in;
		if(isURL(filename))
			{
			URL url= new URL(filename);
			URLConnection con=url.openConnection();
			con.setConnectTimeout(30000);//wait 30 sec
			in=con.getInputStream();
			}
		else
			{
			in=new FileInputStream(new File(filename));
			}
		if(filename.toLowerCase().endsWith(".gz"))
			{
			in=new GZIPInputStream(in);
			}
		return in;
		}
	
	public static BufferedReader openReader(String filename)
	throws IOException
		{
		return new BufferedReader(new InputStreamReader(openInputStream(filename)));
		}
	
	/** creates a new directory in the default tmp directory*/
	public static File createTempDir(String prefix,String suffix) throws IOException
		{
		return createTempDir(prefix, suffix,null);
		}
	
	/** creates a new directory in the given directory*/
	public static File createTempDir(String prefix,String suffix,File parentDir) throws IOException
		{
		File dir= File.createTempFile(prefix, suffix,parentDir);
		if(!(dir.delete()))//it is a FILE, delete it and make it a directory
		    {
		    throw new IOException("Could not delete file: " + dir.getAbsolutePath());
		    }
		if(!(dir.mkdir()))
		    {
		    throw new IOException("Could not create temp directory: " + dir.getAbsolutePath());
		    }
		return dir;
		}
	}
